package com.eascs.spider.dsk.db;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.bson.Document;

import com.eascs.spider.dsk.util.PropertiesUtil;
import com.eascs.spider.dsk.util.StringUtil;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongoSession {
	
	private MongoClient mongoClient = null;
	private MongoDatabase mongoDatabase = null;
	private static MongoSession instance;
	
	private MongoSession(){
		String url = StringUtil.format("mongodb://{}:{}@{}:{}/{}", PropertiesUtil.getConfig("mongodb.user"), PropertiesUtil.getConfig("mongodb.password"), PropertiesUtil.getConfig("mongodb.ip"),PropertiesUtil.getConfig("mongodb.port"), PropertiesUtil.getConfig("mongodb.library"));
		MongoClientURI uri = new MongoClientURI(url);
		this.mongoClient = new MongoClient(uri);
		this.mongoDatabase = mongoClient.getDatabase(PropertiesUtil.getConfig("mongodb.library"));		
	}

	public synchronized static MongoSession getInstance(){
		return instance == null? instance = new MongoSession():instance;
	}
	
	public void set(String collectionName ,Map<String, Object> data){
		MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);
		Document document = new Document(data);
		mongoCollection.insertOne(document);
	}
	
	/**
	 * 检索指定集合中所有文档
	 * @param collectionName
	 */
	public List<String> getUrl(String collectionName){
		MongoCollection<Document> mc = mongoDatabase.getCollection(collectionName);
		FindIterable<Document> findIterable = mc.find();  
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        List<String> list = new ArrayList<>();
        while(mongoCursor.hasNext()){  
           Document document = mongoCursor.next();
           list.add(document.getString("url"));
        }
        return list;
	}
	
	public void getAll(String collectionName){
		MongoCollection<Document> mc = mongoDatabase.getCollection(collectionName);
		FindIterable<Document> findIterable = mc.find();  
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while(mongoCursor.hasNext()){  
           Document document = mongoCursor.next();
        }
	}
}